<?php
class Controller_DataCenter_Marketing extends Controller_Abstract
{
	function actionGAData()
	{
		$this->_view['title'] = 'GA流量数据报表';
		$shop = Shop::find('shop_api_website.ga_profile!=\'\'')->joinLeft('shop_api_website', 'ga_profile, md5', 'shop_api_website.shop_id=shop.id')->asArray()->getAll();
		foreach ($shop as &$s)
		{
			$s['all_order_count'] = GA_Shop_Reg::find('shop_id=?', $s['id'])->getSum('order_count');
			$s['all_reg_count'] = GA_Shop_Reg::find('shop_id=?', $s['id'])->getSum('reg_count');
			$yesterday = strtotime(date('Y-m-d') . ' -1 day');
			$reg = GA_Shop_Reg::find('shop_id=? and date=?', $s['id'], $yesterday)->asArray()->getOne();
			$s['yesterday_reg_count'] = $reg['reg_count'];
			$s['yesterday_order_count'] = $reg['order_count'];
			$ga = GA_Data::find('ga_medium.shop_id=? and ga_data.date=?', $s['id'], $yesterday)
				->joinLeft('ga_campaign', '', 'ga_data.campaign_id=ga_campaign.id')
				->joinLeft('ga_source', '', 'ga_source.id=ga_campaign.source_id')
				->joinLeft('ga_medium', '', 'ga_medium.id=ga_source.medium_id')
				->asArray()->getAll();
			$s['yesterday_ip'] = 0;
			$s['yesterday_pv'] = 0;
			foreach ($ga as $g)
			{
				$s['yesterday_ip'] += $g['ip'];
				$s['yesterday_pv'] += $g['pv'];
			}
		}
		unset($s);
		$this->_view['shop'] = $shop;
	}
	
	function actionReportByDay()
	{
		$this->_view['title'] = 'GA数据日报表';
		$shop = Shop::find('shop_api_website.ga_profile!=\'\'')->joinLeft('shop_api_website', 'ga_profile, md5', 'shop_api_website.shop_id=shop.id')->asArray()->getAll();
		$this->_view['shop'] = $shop;
		$currency = Currency::find('symbol=?', '$')->asArray()->getOne();
		$this->_view['currency_rate'] = $currency['rate'];
		$begin = strtotime($_GET['begin_date']);
		$end = strtotime($_GET['end_date']);
		$data = array();
		for ($p = $end; $p >= $begin; $p -= 86400)
		{
			$temp = array();
			$ga = GA_Data::find('ga_medium.shop_id=? and ga_data.date=?', $_GET['shop_id'], $p)
				->joinLeft('ga_campaign', '', 'ga_data.campaign_id=ga_campaign.id')
				->joinLeft('ga_source', '', 'ga_source.id=ga_campaign.source_id')
				->joinLeft('ga_medium', '', 'ga_medium.id=ga_source.medium_id')
				->asArray()->getAll();
			$temp['ip'] = 0;
			$temp['pv'] = 0;
			$temp['cpc_cost'] = 0;
			$temp['order_count'] = 0;
			$temp['order_amount'] = 0;
			$temp['cpc_order_count'] = 0;
			$temp['cpc_order_amount'] = 0;
			foreach ($ga as $g)
			{
				$temp['ip'] += $g['ip'];
				$temp['pv'] += $g['pv'];
				$temp['cpc_cost'] += $g['cpc_cost'] * $g['adclicks'];
				if ($g['cpc_cost'] > 0)
				{
					$temp['cpc_order_count'] += $g['order_count'];
					$temp['cpc_order_amount'] += $g['order_amount'];
				}
				$temp['order_count'] += $g['order_count'];
				$temp['order_amount'] += $g['order_amount'];
	
			}
			$temp['date'] = $p;
			$reg = GA_Shop_Reg::find('date=? and shop_id=?', $p, $_GET['shop_id'])->asArray()->getOne();
			$temp['reg_count'] = $reg['reg_count'];
			$data[] = $temp;
		}
		$this->_view['data'] = $data;
	}
	
	function actionReportByMonth()
	{
		$this->_view['title'] = 'GA数据月报表';
		$shop = Shop::find('shop_api_website.ga_profile!=\'\'')->joinLeft('shop_api_website', 'ga_profile, md5', 'shop_api_website.shop_id=shop.id')->asArray()->getAll();
		$this->_view['shop'] = $shop;
		$currency = Currency::find('symbol=?', '$')->asArray()->getOne();
		$this->_view['currency_rate'] = $currency['rate'];
		$first = GA_Shop_Reg::find('shop_id=?', $_GET['shop_id'])->order('date asc')->asArray()->getOne();
		$last = GA_Shop_Reg::find('shop_id=?', $_GET['shop_id'])->order('date desc')->asArray()->getOne();
		$first_m = strtotime(date('Y-m-01', $first['date']));
		$last_m = strtotime(date('Y-m-01', $last['date']));
		$data = array();
		for ($p = $last_m; $p >= $first_m; $p = strtotime(date('Y-m-d', $p) . ' -1 month'))
		{
			$temp = array();
			$begin = $p;
			$end = strtotime(date('Y-m-t', $p));
			$temp['date'] = $begin;
			$temp['reg_count'] = GA_Shop_Reg::find('shop_id=? and date>=? and date<=?', $_GET['shop_id'], $begin, $end)->getSum('reg_count');
			$temp['order_count'] = GA_Shop_Reg::find('shop_id=? and date>=? and date<=?', $_GET['shop_id'], $begin, $end)->getSum('order_count');
			$temp['order_amount'] = GA_Shop_Reg::find('shop_id=? and date>=? and date<=?', $_GET['shop_id'], $begin, $end)->getSum('order_amount');
			$data[] = $temp;
		}
		$this->_view['data'] = $data;
	}
	
	function actionReportByDayMedium()
	{
		$this->_view['title'] = 'Medium数据日报表';
		$medium = GA_Medium::find('shop_id=?', $_GET['shop_id'])->asArray()->getAll();
		foreach ($medium as &$m)
		{
			$ga = GA_Data::find('ga_source.medium_id=? and ga_data.date>=? and ga_data.date<=?', $m['id'], strtotime($_GET['begin_date']), strtotime($_GET['end_date']))
				->joinLeft('ga_campaign', '', 'ga_campaign.id=ga_data.campaign_id')
				->joinLeft('ga_source', '', 'ga_campaign.source_id=ga_source.id')
				->asArray()->getAll();
			$m['ip'] = 0;
			$m['pv'] = 0;
			$m['adclicks'] = 0;
			$m['order_count'] = 0;
			$m['order_amount'] = 0;
			foreach ($ga as $g)
			{
				$m['ip'] += $g['ip'];
				$m['pv'] += $g['pv'];
				$m['adclicks'] += $g['adclicks'];
				$m['order_count'] += $g['order_count'];
				$m['order_amount'] += $g['order_amount'];
			}
		}
		unset($m);
		$this->_view['medium'] = $medium;
	}
	
	function actionReportByDaySource()
	{
		$this->_view['title'] = 'Source数据日报表';
		$source = GA_Source::find('medium_id=?', $_GET['medium_id'])->asArray()->getAll();
		foreach ($source as &$s)
		{
			$ga = GA_Data::find('ga_campaign.source_id=? and ga_data.date>=? and ga_data.date<=?', $s['id'], strtotime($_GET['begin_date']), strtotime($_GET['end_date']))
				->joinLeft('ga_campaign', '', 'ga_campaign.id=ga_data.campaign_id')
				->asArray()->getAll();
			$s['ip'] = 0;
			$s['pv'] = 0;
			$s['adclicks'] = 0;
			$s['order_count'] = 0;
			$s['order_amount'] = 0;
			foreach ($ga as $g)
			{
				$s['ip'] += $g['ip'];
				$s['pv'] += $g['pv'];
				$s['adclicks'] += $g['adclicks'];
				$s['order_count'] += $g['order_count'];
				$s['order_amount'] += $g['order_amount'];
			}
		}
		unset($s);
		$this->_view['source'] = $source;
	}
	
	function actionReportByDayCampaign()
	{
		$this->_view['title'] = 'Campaign数据日报表';
		$campaign = GA_Campaign::find('source_id=?', $_GET['source_id'])->asArray()->getAll();
		foreach ($campaign as &$c)
		{
			$ga = GA_Data::find('ga_data.campaign_id=? and ga_data.date>=? and ga_data.date<=?', $c['id'], strtotime($_GET['begin_date']), strtotime($_GET['end_date']))->asArray()->getAll();
			$c['ip'] = 0;
			$c['pv'] = 0;
			$c['adclicks'] = 0;
			$c['order_count'] = 0;
			$c['order_amount'] = 0;
			foreach ($ga as $g)
			{
				$c['ip'] += $g['ip'];
				$c['pv'] += $g['pv'];
				$c['adclicks'] += $g['adclicks'];
				$c['order_count'] += $g['order_count'];
				$c['order_amount'] += $g['order_amount'];
			}
		}
		unset($c);
		$this->_view['campaign'] = $campaign;
	}
	
	function actionEMD()
	{
		$this->_view['title'] = '邮寄EMD报表';
	}
	
	function actionKeySource()
	{
		$this->_view['title'] = '来源关键字';
	}
	
	function actionCustomerList()
	{
		$this->_view['title'] = '客户列表';
		$shop = Shop::find('status=1')->order('shop.sort desc')->asArray()->getAll();
		$this->_view['shop'] = $shop;
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 1;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 100;
		$url_arr = Helper_BSS_Normal::buildCondition();
		$this->_view['url_arr_json'] = json_encode($url_arr);
		$result = Customer_Orders_Info::search($url_arr, $cp, $ps);
		if ($result['ack'] == SUCCESS)
		{
			$page = new Helper_BSS_Page($result['pagination'], url('Datacenter::Marketing/CustomerList', $url_arr));
			$this->_view['page'] = $page->getPage();
			$this->_view['customer'] = $result['data'];
		}
	}
	
	function actionCustomerListDownLoad()
	{
		$this->_view['title'] = '请求下载顾客信息表';
		$url_arr = json_decode($_REQUEST['url_arr_json'], true);
		$result = Customer_Orders_Info::search($url_arr, 0, 0);
		if ($result['ack'] == SUCCESS)
		{
			$data = "客户ID\t邮箱\t全名\t国家\t初次购买时间\t渠道\t订单数\t订单总额\t购买周期\t最近购买日期\t购买次数最多类别\t购买金额最多类别\t最后更新时间\t\n";
			foreach ($result['data'] as $key => $r)
			{
				$data .= trim($r['id']) . "\t";
				$data .= trim($r['email']) . "\t";
				$data .= trim($r['first_order_full_name']) . "\t";
				$data .= trim($r['first_order_country_cn']) . "\t";
				$data .= trim($r['first_order_time']) . "\t";
				$data .= trim($r['shop_name']) . "\t";
				$data .= trim($r['order_total_count']) . "\t";
				$data .= "￥" . number_format($r['order_total_amount_cny']) . "\t";
				$data .= trim($r['order_cycle']) . "\t";
				$data .= trim($r['last_order_time']) . "\t";
				$data .= implode(">", Product_categories::getAncestorNameById($r['order_count_top_categories_id'])) . "\t";
				$data .= implode(">", Product_categories::getAncestorNameById($r['order_amount_top_categories_id'])) . "\t";
				$data .= trim($r['update_time']) . "\t\n";
			}
			$data = iconv("UTF-8", "UTF-16LE", $data);
			$data = "\xFF\xFE" . $data;
			$output_file_name = "customer_order_info.xls";
			header("Content-Type: application/vnd.ms-excel; charset=utf-8");
			header("Content-Type: application/octet-stream");
			header("Content-Type: application/download");
			header('Content-Disposition:inline; filename="' . $output_file_name . '"');
			header("Content-Transfer-Encoding: binary");
			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
			header("Pragma: no-cache");
			echo $data;
			exit;
		}
	}

	function actionCustomerDetail()
	{
		
		$this->_view['title'] = '客户详情';
		
		$customer = Customer::find('customer.id=?', $_GET['id'])
			->joinLeft('website', 'name as website_name', 'website.id=customer.website_id')
			->asArray()->getOne();
		$address = Sales_Order::find('website_id=? and buyer_email=?', $customer['website_id'], $customer['email'])->asArray()->getOne();
		$customer['name'] = $address['buyer_fullname'];
		$customer['address'] = $address['buyer_address1'].','.$address['buyer_city'].','.$address['buyer_state'].','.$address['buyer_zip'].','.$address['buyer_country'];
		$customer['country_cn'] = $address['buyer_country_cn'];
		$customer['phone'] = $address['buyer_phone'];
		$where = 'send_method = ' . Q::ini('appini/send_method/normal/value') . ' and trash_status != ' . Q::ini('appini/sales_order_trash_status/trashed/value') . ' and website_id='.$customer['website_id'] . ' and buyer_email=\'' . $customer['email'] .'\'';
		$order = Sales_Order::find($where)->setColumns('id, number, sale_time, amount, currency_rate')->asArray()->getAll();
		$customer['order_count'] = count($order);
		$customer['order_amount'] = $customer['product_count'] = 0;
		foreach ($order as &$o)
		{
			$customer['order_amount'] += $o['amount'] * $o['currency_rate'];
			$o['product_count'] = Sales_Order_Item::find('sales_order_id=?', $o['id'])->getSum('quantity');
			$customer['product_count'] += $o['product_count'];
		}
		unset($o);
		$customer['visits'] = Logs_Analyser_Products::find('customer_email=?', $customer['email'])->getCount();
		$this->_view['customer'] = $customer;
		if ($_GET['type'] == 'sales_order')
		{
			$this->_view['order'] = $order;
		}
		
		if ($_GET['type'] == 'visits')
		{
			$cp = isset($_GET['cp']) ? $_GET['cp'] : 1;
			$ps = isset($_GET['ps']) ? $_GET['ps'] : 10;
			$select = Logs_Analyser_Products::find('customer_email=?', $customer['email'])
				->joinLeft('website', 'name as website_name', 'website.id=logs_analyser_products.website_id')
				->order('logs_analyser_products.time desc')
				->limitPage($cp, $ps);
			$pagination = $select->getPagination();
			$page = new Helper_BSS_Page($pagination, url('datacenter::report/customerdetail', array('id'=>$_GET['id'],'type'=>'visits')));
			$this->_view['page'] = $page->getPage();
			$visits = $select->asArray()->getAll();
			Helper_BSS_Normal::getProductURL($visits, 'model');
			foreach ($visits as &$v)
			{
				$product = Product::find('number=?', $v['model'])->asArray()->getOne();
				$product_website_info = Product_Website_Info::find('product_id=? and website_id=?', $product['id'], $v['website_id'])->asArray()->getOne();
				$v['categories'] = implode('->', Helper_BSS_Normal::getAncestorNameById($product_website_info['categories_id'], $v['website_id']));
				$v['product_name'] = $product['cn_name'];
			}
			unset($v);
			$this->_view['visits'] = $visits;
		}
		
		if ($_GET['type'] == 'email')
		{
			$email = Email::find('`from`=?', $customer['email'])->asArray()->getAll();
			$this->_view['email'] = $email;
		}
		
		if ($_GET['type'] == 'favorities')
		{
			
		}
	}
}